package com.maben.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理未认证（未登录）的请求：返回 401 错误
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // 设置响应格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        // 设置状态码 401（未授权）
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        // 构建返回的错误信息
        Map<String, Object> error = new HashMap<>();
        error.put("code", 401);
        error.put("msg", "请先登录");

        // 转为 JSON 写入响应
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(error));
    }
}